package com.zy.rpc.common.register.impl;

import com.zy.rpc.common.register.RegistryService;
import com.zy.rpc.common.serviceinfo.ServiceInfo;

import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.framework.CuratorFramework;//用于管理zookeeper连接和操作的客户端
import org.apache.curator.x.discovery.ServiceDiscovery;//用于服务注册和发现的组件
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;

import java.io.IOException;

/**
 * @atuthor zy
 * @date 2023/4/23 18:59
 */
public class RegistryServiceImpl implements RegistryService {

    private CuratorFramework curatorFramework;
    private ServiceDiscovery<ServiceInfo>serviceInfoServiceDiscovery;

    public RegistryServiceImpl(String registryAddress) throws Exception {
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 3);
         curatorFramework = CuratorFrameworkFactory.newClient(registryAddress, retry);
         curatorFramework.start();
        JsonInstanceSerializer<ServiceInfo> instanceSerializer = new JsonInstanceSerializer<>(ServiceInfo.class);
        serviceInfoServiceDiscovery= ServiceDiscoveryBuilder.builder(ServiceInfo.class)
                .client(curatorFramework)
                .basePath("/services")
                .serializer(instanceSerializer)
                .build();
        serviceInfoServiceDiscovery.start();
    }

    @Override
    public void register(ServiceInfo serviceInfo) throws Exception {
        ServiceInstance<ServiceInfo> serviceInstance = ServiceInstance.<ServiceInfo>builder()
                .name(serviceInfo.getServiceName())
                .address(serviceInfo.getAddress())
                .port(serviceInfo.getPort())
                .payload(serviceInfo)
                .build();
        serviceInfoServiceDiscovery.registerService(serviceInstance);
    }

    @Override
    public void unregister(ServiceInfo serviceInfo) throws Exception {
        ServiceInstance<ServiceInfo> serviceInstance = ServiceInstance.<ServiceInfo>builder()
                .name(serviceInfo.getServiceName())
                .address(serviceInfo.getAddress())
                .port(serviceInfo.getPort())
                .payload(serviceInfo)
                .build();
        serviceInfoServiceDiscovery.unregisterService(serviceInstance);
    }

    @Override
    public void destoryAll() throws IOException {
    serviceInfoServiceDiscovery.close();
    curatorFramework.close();
    }
}
